<template>
  <div v-if="options" ref="SelectBoxRef" class="select_container">
    <!--输入框区域-->
    <div @click="isShowOptions = !isShowOptions;scrollToCurrentYear()" class="input_area">
      <!--选中值-->
      <!--      <div :class="currentItem[valueKey] ? 'font_placeholder font_value':'font_placeholder'">-->
      <!--        {{ currentItem[labelKey] ? currentItem[labelKey] : placeholder }}-->
      <!--      </div>-->
      <!-- 前置显示的字段 -->
      <div v-if="isShowFront" class="prepend-slot">
        {{ currentItem[frontLabel] }}
      </div>
      <input @focus="inputFocus" @input="filterOptions()"
             :class="currentItem[valueKey] ? 'font_placeholder font_value':'font_placeholder'"
             v-model="searchText"
             :placeholder="placeholder"/>
      <!--右边的箭头-->
      <div v-if="currentItem[valueKey]" class="arrow right_icon">
        <img src="@/assets/home-img/arrow_down.png" alt=""/>
      </div>
      <!--右边的箭头有值-->
      <div v-if="!currentItem[valueKey]" class="arrow_value right_icon">
        <img src="@/assets/home-img/arrow_down.png" alt=""/>
      </div>


      <div v-if="currentItem[valueKey]" @click="clear" class="clear right_icon">
        <img src="@/assets/edit-ship/delete_gray.png">
      </div>
    </div>

    <!--选项数组-->
    <div v-if="isShowOptions" class="items" id="items">
      <div @click="selectItem(item)" v-for="item in optionsValueArr"
           :class="currentItem[valueKey] == item[valueKey] ? 'item_s item' : 'item'">
        {{ item[labelKey] }}
      </div>
    </div>
  </div>

</template>

<script setup>
import {ref, reactive, watch} from "vue";
import {defineModel, onMounted, onBeforeUnmount} from 'vue'


defineOptions({
  name: "Select",
  inheritAttrs: false,
});

//传进来要处理的item
const props = defineProps({
  //select的选项
  options: {
    type: Array,
    default: null,
  },
  //select的选项显示值字段
  labelKey: {
    type: String,
    default: "label",
  },
  //是否显示前置的字段
  isShowFront: {
    type: Boolean,
    default: false,
  },
  //前置字段的label
  frontLabel: {
    type: String,
    default: "",
  },
  //select的选项实际值字段
  valueKey: {
    type: String,
    default: "value",
  },
  //选择器选择的是什么东西
  selectType: {
    type: String,
    default: null
  }
});

const optionsValueArr = ref([]) //组件内部实际显示的options


// 监听options变化
watch(() => props.options, (newVal) => {
  if (newVal) {
    optionsValueArr.value = newVal;
  }
}, {immediate: true});


//当前选中的项
const currentItem = ref({})

const isShowOptions = ref(false) //是否展示选项列表

//选择项
function selectItem(item) {
  currentItem.value = item
  searchText.value = item[props.labelKey]
  modelValue.value = item[props.valueKey]
  isShowOptions.value = false
  resetFilter()
}

//移除已选择的 和当前绑定值
function clear() {
  currentItem.value = {}
  searchText.value = ""
}

//点击空白除关闭选择弹框
const handleDocumentClick = (event) => {
  // 处理点击事件的逻辑
  if (SelectBoxRef.value && !SelectBoxRef.value.contains(event.target)) {
    isShowOptions.value = false; // 关闭对话框
    // resetFilter()
    searchText.value = currentItem.value[props.labelKey]
  }
};

//整个select组件区域
const SelectBoxRef = ref(null)

//输入框绑定值
const searchText = ref("")
//输入框placeholder项
const placeholder = ref("Select")

// 与父组件绑定值
const modelValue = defineModel()



watch(
  () => modelValue.value,
  (newValue) => {
    if (newValue) {
      if(modelValue.value && optionsValueArr.value){
        //从options数组中根据对应的value找到对应值 设置当前选中项currentItem
// 使用 filter 方法 (适用于可能有多个匹配项)
        const currentItems = optionsValueArr.value.filter(item => item[props.valueKey] == modelValue.value);
        console.log(optionsValueArr.value,modelValue.value,  "currentItems")
        currentItem.value = currentItems[0] ? currentItems[0] : {}; // 取第一个匹配项
        if (currentItem.value) {
          searchText.value = currentItem.value[props.labelKey]
        }
      }
    }
  }
)




//过滤筛选项
function filterOptions() {
  console.log(searchText.value, "searchText.value")
  if (!searchText.value) {
    optionsValueArr.value = props.options
  }
  optionsValueArr.value = props.options.filter(option => {
    return option[props.labelKey].toLowerCase().includes(searchText.value.toLowerCase())
  });
}

//input框聚焦时清空searchText 把placeholder变为当前选择的
function inputFocus() {
  searchText.value = ""
  placeholder.value = currentItem.value[props.labelKey] ? currentItem.value[props.labelKey] : "Select"
}

//点击别处或者是选择了某项 清空输入框和filter过滤项
function resetFilter() {
  optionsValueArr.value = props.options
  placeholder.value = "Select"
}


onMounted(() => {
  document.addEventListener('click', handleDocumentClick);
  if (props.options) {
    optionsValueArr.value = props.options //先初始化一下选项数组
  }
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick);
});


// 在组件挂载后滚动到当前年份
function scrollToCurrentYear() {
  if (props.selectType !== 'year') {
    return
  }
  nextTick(() => {
    const currentYear = new Date().getFullYear();
    const selectEl = document.getElementById('items');
    if (selectEl) {
      // 找到当前年份对应的option索引
      for (let i = 0; i < optionsValueArr.value.length; i++) {
        console.log(parseInt(optionsValueArr.value[i].value) === currentYear)
        if (parseInt(optionsValueArr.value[i].value) == currentYear) {
          // 设置选中并滚动到该选项
          selectEl.selectedIndex = i;
          selectEl.scrollTop = i * 36;
          break;
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.select_container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #F0F2F7;
  padding: 6px 12px;
  border-radius: 8px;
  box-sizing: border-box;
}

.input_area {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .prepend-slot {
    flex-shrink: 0;
  }

  input {
    border: none;
    outline: none;
    background: none;
    box-shadow: none;
    padding: 0;
    margin: 0;
    font-family: inherit;
    font-weight: inherit;
    color: inherit;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    width: 100%;
  }
}

.input_area:hover .arrow {
  display: none;
  transition: all 0.6s;
}

.right_icon {
  width: 16px;
  height: 16px;
  flex-shrink: 0;

  img {
    width: 100% !important;
    height: 100% !important;
  }
}

.clear {
  display: none;
  transition: all 0.6s;
}

.input_area:hover .clear {
  display: flex;
}


.font_placeholder {
  font-size: 14px;
  font-weight: normal;
  line-height: 20px;
  letter-spacing: normal;
  color: #808690;
}

.font_value {
  color: #1C1E24;
}

.items {
  width: 100%;
  position: absolute;
  z-index: 20;
  left: 0;
  top: 105%;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  color: #808690;
  padding: 4px 4px;
  max-height: 200px;
  overflow: auto;

  .item {
    padding: 8px 12px;
    font-size: 14px;
    font-weight: normal;
    line-height: 20px;
    letter-spacing: normal;
    color: #808690;
  }

  .item_s {
    border-radius: 8px;
    background: #E6F9F5;
    font-weight: bold;
    color: #1e90ff;
  }
}
</style>
